package org.easy.bochaai;

import org.easy.bochaai.dto.BochaBaseModel;
import org.easy.bochaai.dto.WebSearchResponse;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Data
public class BochaTemplate {

    private BochaWebSearchClient client;

    public BochaTemplate(BochaWebSearchClient client) {
        this.client = client;
    }


    public List<String> webSearchTop5Summary(String query) {
        return webSearchTop5Summary(query, 250, 5);
    }

    public List<String> webSearchTop5Summary(String query, Integer contentLimit, Integer count) {
        if (contentLimit == null) {
            contentLimit = 1000;
        }

        BochaBaseModel<WebSearchResponse> noLimit = client.webSearch(query, true, "noLimit", count);
        List<String> collect = noLimit.getData().getWebPages().getWebPagesValue().stream().map(WebSearchResponse.WebPagesValue::getSummary).collect(Collectors.toList());
        int finalLimit = contentLimit;
        collect = collect.stream().map(e -> {
            if (e.length() > finalLimit) {
                log.info("搜索{}文本截断原文长{} 截短长{}", query, e.length(), finalLimit);
                return e.substring(0, finalLimit);
            } else {
                return e;
            }
        }).collect(Collectors.toList());
        return collect;
    }

}
